package system

import (
	"errors"
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
	"time"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: Register
//@description: 用户注册
//@param: u model.SysUser
//@return: userInter system.SysUser, err error

type UserService struct{}

func (userService *UserService) Register(u system.SysUser) (userInter system.SysUser, err error) {
	//var user system.SysUser
	//if !errors.Is(global.GVA_DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
	//	return userInter, errors.New("用户名已注册")
	//}

	//var user system.SysUser
	//sql := `
	//		SELECT
	//			*
	//		FROM
	//			public.sys_users
	//		WHERE
	//			username = ?
	//		LIMIT 1
	//		`
	//err = global.GVA_DB.Raw(sql, u.Username).Scan(&user).Error

	var user system.SysUser
	sql := `
			SELECT 
				u.*
			FROM 
				public.sys_users u
			WHERE 
				u.username = ?
			LIMIT 1
			`
	err = global.GVA_DB.Raw(sql, u.Username).Scan(&user).Error

	if user.Username != "" {
		return userInter, errors.New("用户名已注册")
	}

	// 否则 附加uuid 密码hash加密 注册
	u.Password = utils.BcryptHash(u.Password)
	u.UUID = uuid.NewV4()
	//err = global.GVA_DB.Create(&u).Error

	insertSQL := "INSERT INTO public.sys_users (created_at,uuid,username,password,nick_name,authority_id,phone,email,enable) VALUES(?,?,?,?,?,?,?,?,?)"

	err = global.GVA_DB.Exec(insertSQL,
		time.Now(),
		u.UUID,
		u.Username,
		u.Password,
		u.NickName,
		u.AuthorityId,
		u.Phone,
		u.Email,
		u.Enable,
	).Error

	sql2 := `
			SELECT 
				u.*
			FROM 
				public.sys_users u
			WHERE 
				u.username = ?
			LIMIT 1
			`
	err = global.GVA_DB.Raw(sql2, u.Username).Scan(&user).Error

	for _, v := range u.Authorities {
		insertSQL2 := "INSERT INTO public.sys_user_authority (sys_user_id, sys_authority_authority_id) VALUES (?, ?)"
		if err := global.GVA_DB.Exec(insertSQL2, user.ID, v.AuthorityId).Error; err != nil {
			return u, err
		}
	}

	//insertSQL2 := "INSERT INTO public.sys_users SET authority_id = ? WHERE id = ?"
	//err = global.GVA_DB.Exec(sqlUpdate, authorityId, id).Error

	//insertSQL := "INSERT INTO public.sys_user_authority (sys_user_id, sys_authority_authority_id) VALUES (?, ?)"
	//if TxErr := tx.Exec(insertSQL, id, v).Error; TxErr != nil {
	//	return TxErr
	//}
	//
	return u, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: Login
//@description: 用户登录
//@param: u *model.SysUser
//@return: err error, userInter *model.SysUser

/*
func (userService *UserService) Login(u *system.SysUser) (userInter *system.SysUser, err error) {
	if nil == global.GVA_DB {
		return nil, fmt.Errorf("db not init")
	}

	var user system.SysUser
	err = global.GVA_DB.Where("username = ?", u.Username).Preload("Authorities").Preload("Authority").First(&user).Error
	if err == nil {
		if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
			return nil, errors.New("密码错误")
		}
		MenuServiceApp.UserAuthorityDefaultRouter(&user)
	}
	return &user, err
}
*/

func (userService *UserService) Login(u *system.SysUser) (userInter *system.SysUser, err error) {
	if nil == global.GVA_DB {
		return nil, fmt.Errorf("db not init")
	}

	var user system.SysUser
	sql := `
			SELECT 
				u.*
			FROM 
				public.sys_users u
			WHERE 
				u.username = ?
			LIMIT 1
			`
	err = global.GVA_DB.Raw(sql, u.Username).Scan(&user).Error
	sqlAuthority := `
					SELECT 
						a.*
					FROM 
						public.sys_authorities a 
					WHERE 
						a.authority_id = ?
					LIMIT 1
					`
	var authority system.SysAuthority
	err = global.GVA_DB.Raw(sqlAuthority, user.AuthorityId).Scan(&authority).Error
	user.Authority = authority
	sqlAuthorities := `
					SELECT 
						a.*
					FROM 
						public.sys_authorities a
					JOIN 
						sys_user_authority ua ON a.authority_id = ua.sys_authority_authority_id
					WHERE 
						ua.sys_user_id = ?
					`
	var authorities []system.SysAuthority
	err = global.GVA_DB.Raw(sqlAuthorities, user.ID).Scan(&authorities).Error
	user.Authorities = authorities
	// err = global.GVA_DB.Where("username = ?", u.Username).Preload("Authorities").Preload("Authority").First(&user).Error
	if err == nil {
		if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
			return nil, errors.New("密码错误")
		}
		MenuServiceApp.UserAuthorityDefaultRouter(&user)
	}
	return &user, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: ChangePassword
//@description: 修改用户密码
//@param: u *model.SysUser, newPassword string
//@return: userInter *model.SysUser,err error
/*
func (userService *UserService) ChangePassword(u *system.SysUser, newPassword string) (userInter *system.SysUser, err error) {
	var user system.SysUser
	if err = global.GVA_DB.Where("id = ?", u.ID).First(&user).Error; err != nil {
		return nil, err
	}
	if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
		return nil, errors.New("原密码错误")
	}
	user.Password = utils.BcryptHash(newPassword)
	err = global.GVA_DB.Save(&user).Error
	return &user, err

}
*/
func (userService *UserService) ChangePassword(u *system.SysUser, newPassword string) (userInter *system.SysUser, err error) {
	var user system.SysUser
	// if err = global.GVA_DB.Where("id = ?", u.ID).First(&user).Error; err != nil {
	// 	return nil, err
	// }
	sql := "SELECT * FROM public.sys_users WHERE id = ? LIMIT 1"
	if err = global.GVA_DB.Raw(sql, u.ID).Scan(&user).Error; err != nil {
		return nil, err
	}
	if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
		return nil, errors.New("原密码错误")
	}
	user.Password = utils.BcryptHash(newPassword)
	// err = global.GVA_DB.Save(&user).Error
	//sql2 := "UPDATE sys_users SET password = ? WHERE id = ?"
	sql2 := "UPDATE public.sys_users SET password = ? WHERE id = ?"
	err = global.GVA_DB.Exec(sql2, user.Password, user.ID).Error
	return &user, err

}

func (userService *UserService) ChangeDelPassword(newPassword string) (err error) {

	sql := "UPDATE public.delpasswordtable SET delpassword = ?"
	err = global.GVA_DB.Exec(sql, newPassword).Error
	return err

}

func (userService *UserService) ConfirmPassword(delPassword string) (err error) {
	var del string
	sql := "SELECT * FROM public.delpasswordtable"
	if err = global.GVA_DB.Raw(sql).Scan(&del).Error; err != nil {
		return err
	}
	if del != delPassword {
		return errors.New("密码错误")
	}
	return err

}

func (userService *UserService) GetDelPassword() (delPassword string, err error) {
	var del string
	sql := "SELECT * FROM public.delpasswordtable"
	if err = global.GVA_DB.Raw(sql).Scan(&del).Error; err != nil {
		return del, err
	}
	return del, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetUserInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: err error, list interface{}, total int64
/*
func (userService *UserService) GetUserInfoList(info request.PageInfo) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&system.SysUser{})
	var userList []system.SysUser
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("Authorities").Preload("Authority").Find(&userList).Error
	return userList, total, err
}
*/
func (userService *UserService) GetUserInfoList(info request.PageInfo) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	// 分页查询用户列表
	sql := `
        SELECT 
            u.*
        FROM 
            public.sys_users u
        LIMIT 
            ? OFFSET ?
    `
	var userList []system.SysUser
	err = global.GVA_DB.Raw(sql, limit, offset).Scan(&userList).Error
	if err != nil {
		return
	}

	// 更新总用户数
	sqlCount := "SELECT COUNT(*) FROM public.sys_users"
	err = global.GVA_DB.Raw(sqlCount).Count(&total).Error
	if err != nil {
		return
	}

	// 对于每个用户，查询他们的 Authority 和 Authorities
	for i, user := range userList {
		// 查询 Authority
		sqlAuthority := `
            SELECT 
                a.*
            FROM 
                public.sys_authorities a 
            WHERE 
                a.authority_id = ?
            LIMIT 1
        `
		var authority system.SysAuthority
		err = global.GVA_DB.Raw(sqlAuthority, user.AuthorityId).Scan(&authority).Error
		if err != nil {
			return
		}
		userList[i].Authority = authority

		// 查询 Authorities
		sqlAuthorities := `
            SELECT 
                a.*
            FROM 
                public.sys_authorities a
            JOIN 
                public.sys_user_authority ua ON a.authority_id = ua.sys_authority_authority_id
            WHERE 
                ua.sys_user_id = ?
        `
		var authorities []system.SysAuthority
		err = global.GVA_DB.Raw(sqlAuthorities, user.ID).Scan(&authorities).Error
		if err != nil {
			return
		}
		userList[i].Authorities = authorities
	}

	return userList, total, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: SetUserAuthority
//@description: 设置一个用户的权限
//@param: uuid uuid.UUID, authorityId string
//@return: err error
/*
func (userService *UserService) SetUserAuthority(id uint, authorityId uint) (err error) {
	assignErr := global.GVA_DB.Where("sys_user_id = ? AND sys_authority_authority_id = ?", id, authorityId).First(&system.SysUserAuthority{}).Error
	if errors.Is(assignErr, gorm.ErrRecordNotFound) {
		return errors.New("该用户无此角色")
	}
	err = global.GVA_DB.Where("id = ?", id).First(&system.SysUser{}).Update("authority_id", authorityId).Error
	return err
}
*/
func (userService *UserService) SetUserAuthority(id uint, authorityId uint) (err error) {
	// 检查 SysUserAuthority 表中是否存在指定的用户和权限关系
	sqlCheck := `
        SELECT * FROM public.sys_user_authority
        WHERE sys_user_id = ? AND sys_authority_authority_id = ?
        LIMIT 1
    `
	var userAuthority system.SysUserAuthority
	assignErr := global.GVA_DB.Raw(sqlCheck, id, authorityId).Scan(&userAuthority).Error
	if errors.Is(assignErr, gorm.ErrRecordNotFound) {
		return errors.New("该用户无此角色")
	}

	// 更新 SysUser 表中的 authority_id 字段
	sqlUpdate := "UPDATE public.sys_users SET authority_id = ? WHERE id = ?"
	err = global.GVA_DB.Exec(sqlUpdate, authorityId, id).Error

	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: SetUserAuthorities
//@description: 设置一个用户的权限
//@param: id uint, authorityIds []string
//@return: err error
/*
func (userService *UserService) SetUserAuthorities(id uint, authorityIds []uint) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		TxErr := tx.Delete(&[]system.SysUserAuthority{}, "sys_user_id = ?", id).Error
		if TxErr != nil {
			return TxErr
		}
		var useAuthority []system.SysUserAuthority
		for _, v := range authorityIds {
			useAuthority = append(useAuthority, system.SysUserAuthority{
				SysUserId: id, SysAuthorityAuthorityId: v,
			})
		}
		TxErr = tx.Create(&useAuthority).Error
		if TxErr != nil {
			return TxErr
		}
		TxErr = tx.Where("id = ?", id).First(&system.SysUser{}).Update("authority_id", authorityIds[0]).Error
		if TxErr != nil {
			return TxErr
		}
		// 返回 nil 提交事务
		return nil
	})
}
*/
func (userService *UserService) SetUserAuthorities(id uint, authorityIds []uint) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 删除特定用户的所有权限关联
		deleteSQL := "DELETE FROM public.sys_user_authority WHERE sys_user_id = ?"
		if TxErr := tx.Exec(deleteSQL, id).Error; TxErr != nil {
			return TxErr
		}

		// 为用户创建新的权限关联
		for _, v := range authorityIds {
			insertSQL := "INSERT INTO public.sys_user_authority (sys_user_id, sys_authority_authority_id) VALUES (?, ?)"
			if TxErr := tx.Exec(insertSQL, id, v).Error; TxErr != nil {
				return TxErr
			}
		}

		// 更新用户的 authority_id 字段
		if len(authorityIds) > 0 {
			updateSQL := "UPDATE public.sys_users SET authority_id = ? WHERE id = ?"
			if TxErr := tx.Exec(updateSQL, authorityIds[0], id).Error; TxErr != nil {
				return TxErr
			}
		}

		// 返回 nil 提交事务
		return nil
	})
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteUser
//@description: 删除用户
//@param: id float64
//@return: err error
/*
func (userService *UserService) DeleteUser(id int) (err error) {
	var user system.SysUser
	err = global.GVA_DB.Where("id = ?", id).Delete(&user).Error
	if err != nil {
		return err
	}
	err = global.GVA_DB.Delete(&[]system.SysUserAuthority{}, "sys_user_id = ?", id).Error
	return err
}
*/
func (userService *UserService) DeleteUser(id int) (err error) {
	// 删除 sys_users 表中的用户记录
	deleteUserSQL := "DELETE FROM public.sys_users WHERE id = ?"
	if err = global.GVA_DB.Exec(deleteUserSQL, id).Error; err != nil {
		return err
	}

	// 删除与该用户相关联的 sys_user_authority 记录
	deleteUserAuthoritySQL := "DELETE FROM public.sys_user_authority WHERE sys_user_id = ?"
	err = global.GVA_DB.Exec(deleteUserAuthoritySQL, id).Error

	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: SetUserInfo
//@description: 设置用户信息
//@param: reqUser model.SysUser
//@return: err error, user model.SysUser
/*
func (userService *UserService) SetUserInfo(req system.SysUser) error {
	return global.GVA_DB.Updates(&req).Error
}
*/
func (userService *UserService) SetUserInfo(req system.SysUser) error {
	updateSQL := `
        UPDATE public.sys_users
        SET 
            updated_at = ?, 
            nick_name = ?, 
            header_img = ?, 
            phone = ?, 
            email = ?, 
            side_mode = ?, 
            enable = ?
        WHERE id = ?
    `
	return global.GVA_DB.Exec(updateSQL,
		time.Now(),
		req.NickName,
		req.HeaderImg,
		req.Phone,
		req.Email,
		req.SideMode,
		req.Enable,
		req.ID,
	).Error
}

//@author: [piexlmax](https://github.com/piexlmax)
//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: GetUserInfo
//@description: 获取用户信息
//@param: uuid uuid.UUID
//@return: err error, user system.SysUser
/*
func (userService *UserService) GetUserInfo(uuid uuid.UUID) (user system.SysUser, err error) {
	var reqUser system.SysUser
	err = global.GVA_DB.Preload("Authorities").Preload("Authority").First(&reqUser, "uuid = ?", uuid).Error
	if err != nil {
		return reqUser, err
	}
	MenuServiceApp.UserAuthorityDefaultRouter(&reqUser)
	return reqUser, err
}
*/
func (userService *UserService) GetUserInfo(uuid uuid.UUID) (user system.SysUser, err error) {
	// 查询用户信息
	userSQL := `
        SELECT 
            *
        FROM 
            public.sys_users 
        WHERE 
            uuid = ?
        LIMIT 1
    `
	err = global.GVA_DB.Raw(userSQL, uuid).Scan(&user).Error
	if err != nil {
		return user, err
	}

	// 查询用户的 Authority
	authoritySQL := `
        SELECT 
            a.*
        FROM 
            public.sys_authorities a
        WHERE 
            a.authority_id = ?
        LIMIT 1
    `
	var authority system.SysAuthority
	err = global.GVA_DB.Raw(authoritySQL, user.AuthorityId).Scan(&authority).Error
	if err != nil {
		return user, err
	}
	user.Authority = authority

	// 查询用户的 Authorities
	authoritiesSQL := `
        SELECT 
            a.*
        FROM 
            public.sys_authorities a
        JOIN 
            public.sys_user_authority ua ON a.authority_id = ua.sys_authority_authority_id
        WHERE 
            ua.sys_user_id = ?
    `
	var authorities []system.SysAuthority
	err = global.GVA_DB.Raw(authoritiesSQL, user.ID).Scan(&authorities).Error
	if err != nil {
		return user, err
	}
	user.Authorities = authorities

	MenuServiceApp.UserAuthorityDefaultRouter(&user)
	return user, err
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: FindUserById
//@description: 通过id获取用户信息
//@param: id int
//@return: err error, user *model.SysUser
/*
func (userService *UserService) FindUserById(id int) (user *system.SysUser, err error) {
	var u system.SysUser
	err = global.GVA_DB.Where("`id` = ?", id).First(&u).Error
	return &u, err
}
*/
func (userService *UserService) FindUserById(id int) (user *system.SysUser, err error) {
	var u system.SysUser
	sql := `
        SELECT 
            *
        FROM 
            public.sys_users
        WHERE 
            id = ?
        LIMIT 1
    `
	err = global.GVA_DB.Raw(sql, id).Scan(&u).Error
	return &u, err
}

//@author: [SliverHorn](https://github.com/SliverHorn)
//@function: FindUserByUuid
//@description: 通过uuid获取用户信息
//@param: uuid string
//@return: err error, user *model.SysUser
/*
func (userService *UserService) FindUserByUuid(uuid string) (user *system.SysUser, err error) {
	var u system.SysUser
	if err = global.GVA_DB.Where("`uuid` = ?", uuid).First(&u).Error; err != nil {
		return &u, errors.New("用户不存在")
	}
	return &u, nil
}
*/
func (userService *UserService) FindUserByUuid(uuid string) (user *system.SysUser, err error) {
	var u system.SysUser
	sql := `
        SELECT 
            *
        FROM 
            public.sys_users
        WHERE 
            uuid = ?
        LIMIT 1
    `
	err = global.GVA_DB.Raw(sql, uuid).Scan(&u).Error
	if err != nil {
		return &u, errors.New("用户不存在")
	}
	return &u, nil
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: resetPassword
//@description: 修改用户密码
//@param: ID uint
//@return: err error
/*
func (userService *UserService) ResetPassword(ID uint) (err error) {
	err = global.GVA_DB.Model(&system.SysUser{}).Where("id = ?", ID).Update("password", utils.BcryptHash("123456")).Error
	return err
}
*/
func (userService *UserService) ResetPassword(ID uint) (err error) {
	// 先对密码进行加密
	hashedPassword := utils.BcryptHash("123456")

	// 更新用户的密码
	updateSQL := "UPDATE public.sys_users SET password = ? WHERE id = ?"
	err = global.GVA_DB.Exec(updateSQL, hashedPassword, ID).Error

	return err
}
